package vader.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.TypeUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fancy.cc.common.api.CommonPage;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * @Author: leige@mail.thefancyapp.com
 * @since 2021-3-9 16:28
 */
public class ConvertTypeUtil {

    public static <T> CommonPage<T> convertPageToPageHelper(Page<T> page){
        List<T> records = page.getRecords();
        long size = page.getSize();
        long total = page.getTotal();
        long current = page.getCurrent();
        CommonPage<T> resultPage = new CommonPage<>();
        resultPage.setPageNum((int) current);
        resultPage.setTotal(total);
        resultPage.setPageSize((int) size);
        resultPage.setList(records);
        resultPage.setTotalPage(new Double(Math.ceil((float)total / size)).intValue());
        return resultPage;
    }


    /**
     * @auth Mickey
     * @param targetType - 目标集合元素类型
     * @param value - 当前value
     * @param <T>
     * @return
     */
    public static <T> CommonPage<T> commonPageConvert(Class<T> targetType, CommonPage value) {
        final Type[] typeArguments = TypeUtil.getTypeArguments(value.getClass());
        final Type[] targetTypeArguments = TypeUtil.getTypeArguments(targetType.getClass());
        if (null != typeArguments
                && 1 == typeArguments.length
                && Objects.equals(targetTypeArguments[0], typeArguments[0])) {
            //对于键值对类型一致的CommonPage对象，不再做转换，直接返回原对象
            return value;
        }
        value.setList((ArrayList) CollUtil.addAll(new ArrayList<>(), value.getList(), targetType));
        return value;
    }
}
